<template>
  <view class="relative bg-white order-list flex flex-col h-full">
    <nav-bar color="white" bg-color="black" title="报表" show-back>
      <view class="search-in-bar w-fit m-auto">
        <u-tabs
          :current="currTab"
          @change="onNavTabChange"
          :list="[{ name: '营收报表' } /* , { name: '统计数据' } */]"
          active-style="color: var(--kui-color-theme);font-size:10rpx;"
          inactive-style="color: lightgray;font-size:10rpx;"
          line-width="20rpx"
          line-color="var(--kui-color-theme)"
        ></u-tabs>
      </view>
    </nav-bar>

    <view class="container" v-if="currTab == 0">
      <u-row gutter="10rpx" :customStyle="rowFillterBar">
        <u-col span="3">
          <uni-data-select
            v-model="currSelectValue"
            :localdata="dateTypeList"
            :clear="false"
            @change="changeSelect"
          ></uni-data-select>
        </u-col>
        <u-col span="3" v-if="showCustomDate">
          <uni-datetime-picker type="daterange" @change="changeDataSelect" />
        </u-col>
        <u-col span="1">
          <u-button type="info" color="lightgrey" @click="resetFilter">重置</u-button>
        </u-col>
        <u-col span="1">
          <u-button type="primary" color="#2f90ff" @click="printPreview">打印预览</u-button>
        </u-col>
        <!-- <u-col span="2">
        <u-button type="primary" color="orange" @click="addItem">打印支付收款对账单</u-button>
      </u-col> -->
      </u-row>

      <u-row>
        <view class="w-full head-box">
          <info-panel ref="refInfoPanel" :config="infoConfig" bg-color="#f5faff" />
          <view class="mt-5rpx">
            <info-panel ref="refInfoPanelFixed" :config="infoFixedConfig" bg-color="#fbb64d31" />
          </view>
        </view>
      </u-row>

      <u-row customStyle="flex:1;height:100%;align-items: baseline;">
        <view class="px-12rpx w-full box-border flex flex-col h-full">
          <uni-table :loading="pageStatus.loading" class="table-height" stripe emptyText="暂无更多数据" :border="true">
            <!-- 表头行 -->
            <uni-tr class="thead-tr">
              <uni-th align="center">营收类别</uni-th>
              <uni-th align="center">数量</uni-th>
              <uni-th align="center">金额（元）</uni-th>

              <uni-th align="center">收入明细</uni-th>
              <uni-th align="center">数量</uni-th>
              <uni-th align="center">金额（元）</uni-th>

              <uni-th align="center">充值明细</uni-th>
              <uni-th align="center">数量</uni-th>
              <uni-th align="center">金额（元）</uni-th>

              <uni-th align="center">消费类别</uni-th>
              <uni-th align="center">数量</uni-th>
              <uni-th align="center">金额（元）</uni-th>
            </uni-tr>
            <!-- 表格数据行 -->
            <template v-for="(item, index) in tableList" :key="index">
              <uni-tr>
                <!-- expandSubItems  v-if="item.parentId ? (item.parentId == currOpenId) : true"-->
                <uni-td align="center">{{ getRowData(item, "turnover", "name") }}</uni-td>
                <uni-td align="center">{{ getRowData(item, "turnover", "num") }}</uni-td>
                <uni-td align="center">{{ getRowData(item, "turnover", "money") }}</uni-td>

                <uni-td align="left">
                  <!-- 有子项 -->
                  <view v-if="isSubItems(item)" @click="openSubTable(item, index)" class="flex justify-between">
                    <text>{{ getRowData(item, "orderItems", "name") }}</text>
                    <u-icon
                      :name="currParentId.includes(getRowData(item, 'orderItems', 'id')) ? 'arrow-down' : 'arrow-right'"
                      color="lightgrey"
                    ></u-icon>
                  </view>
                  <!-- 子项本身 -->
                  <view v-else-if="getRowData(item, 'orderItems', 'parentId')" :class="{ 'ml-10rpx': true }">
                    {{ getRowData(item, "orderItems", "name") }}</view
                  >
                  <!-- 无子项 -->
                  <view v-else> {{ getRowData(item, "orderItems", "name") }}</view>
                </uni-td>
                <uni-td align="center">
                  <text :class="{ desalination: getRowData(item, 'orderItems', 'num') == 0 }">
                    {{ getRowData(item, "orderItems", "num") }}
                  </text>
                </uni-td>
                <uni-td align="center">{{ getRowData(item, "orderItems", "money") }}</uni-td>

                <uni-td align="center">{{ getRowData(item, "recharge", "name") }}</uni-td>
                <uni-td align="center">{{ getRowData(item, "recharge", "num") }}</uni-td>
                <uni-td align="center">{{ getRowData(item, "recharge", "money") }}</uni-td>

                <uni-td align="center">{{ getRowData(item, "consumer", "name") }}</uni-td>
                <uni-td align="center">{{ getRowData(item, "consumer", "num") }}</uni-td>
                <uni-td align="center">{{ getRowData(item, "consumer", "money") }}</uni-td>
              </uni-tr>
            </template>

            <!-- 合计 -->
            <uni-tr class="thead-tr flxed-bottom">
              <uni-td align="center">合计</uni-td>
              <uni-td align="center">{{ getSum("turnover", "num") }}</uni-td>
              <uni-td align="center">{{ getSum("turnover", "money") }}</uni-td>

              <uni-td align="center">合计</uni-td>
              <uni-td align="center">{{ getSum("orderItems", "num") }}</uni-td>
              <uni-td align="center">{{ getSum("orderItems", "money") }}</uni-td>

              <uni-td align="center">合计</uni-td>
              <uni-td align="center">{{ getSum("recharge", "num") }}</uni-td>
              <uni-td align="center">{{ getSum("recharge", "money") }}</uni-td>

              <uni-td align="center">合计</uni-td>
              <uni-td align="center">{{ getSum("consumer", "num") }}</uni-td>
              <uni-td align="center">{{ getSum("consumer", "money") }}</uni-td>
            </uni-tr>
          </uni-table>
        </view>
      </u-row>

      <com-print-preview ref="refPreintPreview" />
    </view>
    <view class="container" v-else>
      <dataStatistics />
    </view>
  </view>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, computed } from "vue";
import { revenueReport, quotaOrderRevenueReport } from "@/api";
import { formatMoney, obj2urlParams } from "@/utils/util";
import comPrintPreview from "./com-print-preview.vue";
import dataStatistics from "./data-statistics.vue";
import dayjs from "dayjs";
import { useStore } from "vuex";

const store = useStore();

const rowFillterBar = `
    padding:8rpx;
    position: sticky;
    top: 0;
    background: white;
    z-index: 2;
`;

const pageStatus = reactive({
  loading: false,
});

const filterPam = reactive({
  // name: "", // 菜品名称 keyword
  startDate: "",
  endDate: "",
  selectType: 0,
});

const resetFilter = () => {
  filterPam.startDate = "";
  filterPam.endDate = "";
  getPageData();
};

const tableList = reactive([]);
const refInfoPanel = ref();
const refInfoPanelFixed = ref();

const getPageData = async () => {
  pageStatus.loading = true;
  try {
    const pam = {
      // descs: "create_time",
      ...filterPam,
    };
    const { data, success } = await revenueReport(pam);
    // console.log(data);
    if (!success) throw new Error("获取数据失败");
    // tableList = tableRows(data);
    tableList.splice(0, tableList.length, ...tableRows(data));
    // 更新头部数据
    refInfoPanel.value.updateValues(infoConfig, data, 0);
    pageStatus.loading = false;

    // 获取 固定营收统计报告
    getFixedRevenueReport();
  } catch (error) {
    pageStatus.loading = false;
    console.error(error);
  }
};

// 获取 固定营收统计报告
const getFixedRevenueReport = async () => {
  pageStatus.loading = true;
  try {
    const { businessId } = store.getters.businessInfo;
    const pam = {
      ...filterPam,
      businessId: businessId,
      // deviceName: store.getters.deviceId,
    };
    const { data, success } = await quotaOrderRevenueReport(pam);
    if (!success) throw new Error("获取数据失败");
    // 更新头部 第二位置数据
    refInfoPanelFixed.value.updateValues(infoFixedConfig, data, 0);
    pageStatus.loading = false;
    console.log("固定营收统计报告", data);
  } catch (error) {
    pageStatus.loading = false;
    console.error(error);
  }
};

// 头部信息信息面板组件
const infoConfig = [
  {
    children: [
      {
        type: "txt-double",
        title: ["营业额：", "营业收入：", "实际收入：", "优惠金额：", "现金金额："],
        key: ["turnoverAmount", "revenue", "realIncome", "discountAmount", "cashAmount"],
        dict: [],
        formatter: (key, value) => {
          // if ([].includes(key)) {
          return formatMoney(value) + " 元";
          // }
          // return value;
        },
      },
      {
        type: "txt-double",
        title: ["订单数量：", "订单退款：", "通道费：", "会员储蓄余额：", ""],
        key: ["orderQuantity", "orderRefunds", "channelFee", "memberSavingsBalance", "__empty__"],
        dict: [],
        formatter: (key, value) => {
          if (["orderRefunds", "channelFee", "memberSavingsBalance"].includes(key)) {
            return formatMoney(value) + " 元";
          }
          if (key === "orderQuantity") {
            return value + " 单";
          }
          if (key === "__empty__") {
            return "";
          }
          return value;
        },
      },
    ],
  },
];

// 头部信息第二位置（固定营收）
const infoFixedConfig = [
  {
    title: "固定消费营收统计",
    children: [
      {
        type: "txt-double",
        title: ["订单数量：", "订单金额：", "优惠金额：", "实收金额：", "现金金额：", "订单退款："],
        key: ["orderQuantity", "revenue", "discountAmount", "realIncome", "cashAmount", "orderRefunds"],
        dict: [],
        formatter: (key, value) => {
          if (key != "orderQuantity") {
            return formatMoney(value) + " 元";
          } else {
            return (value || 0) + " 单";
          }
        },
      },
    ],
  },
];

const refPreintPreview = ref();
const printPreview = () => {
  uni.navigateTo({ url: "./print-preview?" + obj2urlParams(filterPam) });
  // console.log("打印预览",  "./print-preview?" + obj2urlParams(filterPam));

  // refPreintPreview.value.open(filterPam);
};

/**
 * 筛选
 * 接口地址 http://172.10.0.21:32881/doc.html#/%E5%B1%85%E5%AE%B6-%E8%AE%A2%E5%8D%95%E6%A8%A1%E5%9D%97/%E5%8A%A9%E9%A4%90%E8%AE%A2%E5%8D%95/revenueReportUsingGET
 * */
// selectType	查询类型（0今日1本周2本月3自定义4前天5昨天6上个月）
const currSelectValue = ref("today");
const dateTypeList = [
  { text: "今日", value: "today", selectType: 0, range: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")] },
  {
    text: "昨日",
    value: "yesterday",
    selectType: 5,
    range: [dayjs().subtract(1, "days").format("YYYY-MM-DD"), dayjs().subtract(1, "days").format("YYYY-MM-DD")],
  },
  {
    text: "前天",
    value: "beforeYesterday",
    selectType: 4,
    range: [dayjs().subtract(2, "days").format("YYYY-MM-DD"), dayjs().subtract(2, "days").format("YYYY-MM-DD")],
  },
  {
    text: "本周",
    value: "week",
    selectType: 1,
    range: [dayjs().startOf("week").format("YYYY-MM-DD"), dayjs().endOf("week").format("YYYY-MM-DD")],
  },
  {
    text: "本月",
    value: "month",
    selectType: 2,
    range: [dayjs().startOf("month").format("YYYY-MM-DD"), dayjs().endOf("month").format("YYYY-MM-DD")],
  },
  {
    text: "上月",
    value: "premonth",
    selectType: 6,
    range: [
      dayjs().subtract(1, "month").startOf("month").format("YYYY-MM-DD"),
      dayjs().subtract(1, "month").endOf("month").format("YYYY-MM-DD"),
    ],
  },
  {
    text: "自定义",
    value: "custom",
    selectType: -1 /** (不是) */,
    range: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")],
  },
];

const showCustomDate = ref(false);
const changeSelect = (e) => {
  // console.log("changeSelect>>", e);
  // 找到当前选中项的dateTypeList值，
  const selectItem = dateTypeList.find((item) => item.value === e);
  currSelectValue.value = e;

  filterPam.selectType = selectItem.selectType;
  [filterPam.startDate, filterPam.endDate] = selectItem.range;

  showCustomDate.value = e === "custom";

  if (e != "custom") getPageData();
};
const changeDataSelect = (e) => {
  // console.log("changeDataSelect>>", e);
  [filterPam.startDate, filterPam.endDate] = e;
  getPageData();
};

// 顶部tab切换
const onNavTabChange = ({ index }) => {
  currTab.value = index;
};

onMounted(async () => {
  // 默认查询今日数据
  [filterPam.startDate, filterPam.endDate] = dateTypeList[0].range;
  getPageData();
});

// 将接口返回的报表分组数据，横向合并成表格列表数据；
const tableRows = (report: Api.Report.Report) => {
  // 定义表格列名，用于结果中的键名
  const columnNames = ["consumer", "orderItems", "recharge", "turnover"];
  // 获取所有数组中最大的长度，用于确定结果数组的长度
  const maxLength = Math.max(
    report.consumer.length,
    report.orderItems.length,
    report.recharge.length,
    report.turnover.length
  );

  // 初始化结果数组，长度为最大长度，每个元素为一个对象，键为列名，初始值为null
  const result: Record<string, Api.Report.BaseReport | null>[] = Array.from({ length: maxLength }, () =>
    Object.fromEntries(columnNames.map((columnName) => [columnName, null]))
  );

  // 填充结果数组
  for (let i = 0; i < maxLength; i++) {
    result[i].consumer = report.consumer[i] ?? null;
    result[i].orderItems = report.orderItems[i] ?? null;
    result[i].recharge = report.recharge[i] ?? null;
    result[i].turnover = report.turnover[i] ?? null;
  }

  return result;
};
const getRowData = (row: any, typeKey: string, key: string) => {
  // 限制字符最大长度
  const maxLength = 10;
  if (!row) return "";
  const rowTypeData = row[typeKey];
  if (!key) return rowTypeData || {};
  const rowData = rowTypeData?.[key];

  if (key === "num" && rowTypeData?.name && !rowData) return 0;
  if (key === "money" && rowTypeData?.name && !rowData) return "0.00";
  if (key === "name" && rowData?.length > maxLength) return rowData.slice(0, maxLength) + "...";

  return rowData || "";
};

const currParentId: string[] = reactive([]);

const openSubTable = (item: any, index: number) => {
  const source = item.orderItems;

  // 查找是否已插入过子数据，如果已插入过，则删除

  if (currParentId.includes(source.id)) {
    tableList.splice(index + 1, source?.children.length);
    currParentId.splice(currParentId.indexOf(source.id), 1);
  } else {
    // 在指定位置插入数据
    const childrens: any = [];
    source.children.map((child: any) => {
      childrens.push({
        consumer: {},
        orderItems: child,
        recharge: {},
        turnover: {},
      });
    });

    tableList.splice(index + 1, 0, ...childrens);
    currParentId.push(source.id);
    // console.log("openSubTable  <<>>>>", resultItem, item);
  }
};

// 统计合计
const getSum = computed(() => {
  return (typeKey: string, key: string) => {
    const sum = tableList.reduce((pre, cur) => {
      const rowData = cur[typeKey]?.[key] || 0;
      // 需要过滤 是子表单数据的项目
      if (cur[typeKey]?.parentId) return pre;
      if (rowData !== "") return pre + Number(rowData);
      else return pre;
    }, 0);
    if (key === "money") return sum.toFixed(2);
    else return sum;
  };
});

// 是否处理子项
const isSubItems = computed(() => {
  return (item: any) => {
    /**
     * 额外判断条件, 因为有部分数据是子项，但是 没有 parentId 🫠,又没其他特征码,这里去除这些数据的展开显示
     */
    const whiteList = ["会员卡充值", "会员卡押", "会员卡退卡", "餐补补贴"];
    if (whiteList.includes(item?.orderItems?.name)) return false;
    else return getRowData(item, "orderItems", "children");
  };
});

const currTab = ref(0);
</script>

<style lang="scss" scoped>
.container{
  /** navbar 是 10vh */
  max-height: 90vh;
  overflow-y: auto;
}

::v-deep .uni-select__selector-scroll {
  max-height: 80vh !important;
}

.order-list {
  height: 100%;
  ::v-deep .u-search__content {
    border-top-right-radius: 0 !important;
    border-bottom-right-radius: 0 !important;
    margin-right: -10px;
    height: 25rpx;

    // .u-search__content__icon {
    //   display: none;
    // }

    .uni-input-input {
      height: 25rpx;
    }
  }

  ::v-deep .u-search__action {
    background: var(--kui-color-theme);
    max-height: 25rpx;
    height: 25rpx;
    border-radius: 3rpx;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 5rpx;
    font-size: 10rpx;
  }

  ::v-deep .u-button {
    border-radius: 3rpx;
    height: 25rpx;
  }
}

::v-deep .uni-table-td,
.uni-table-th {
  font-size: 10rpx;
  line-height: 12rpx;
}

.fixed-left {
  position: sticky;
  background-color: white;
  left: 0;
}

.fixed-right {
  // display: flex;
  position: sticky;
  right: 0;

  &.thead {
    display: block;
    box-shadow: -6px 0px 5px 0px #e7e7e7;
  }

  &.tdata {
    background-color: white;
    box-shadow: -6px 0px 5px 0px #e7e7e7;
  }
  ::v-deep .u-button {
    margin-right: 5rpx;
    height: 20rpx;
  }
}

.flxed-bottom {
  position: sticky;
  bottom: 0;
  font-weight: bold;
  background-color: var(--kui-color-theme-light) !important;
}

.form-item-btns {
  position: relative;
  // ::v-deep .kingon-select-menu{
  //   font-size: 10rpx;
  //   z-index: 6;
  // }
}

.thead-tr {
  position: sticky;
  top: 0;
  z-index: 1;
}

.desalination {
  color: lightgrey;
}

.table-height {
  // max-height: 60vh;
  flex: auto;

  ::v-deep &.uni-table-scroll {
    border: 1px #ebeef5 solid;
  }
}

.pagination-box {
  padding: 10rpx;
  display: flex;
  flex-direction: row;
  justify-content: right;
  position: sticky;
  bottom: 0;
  background: white;
}

.head-box {
  background-color: white;
  padding: 10rpx;
  padding-top: 0;
}
</style>
